package com.rock.code.province.tj.busi.demo;


import com.rock.code.province.tj.busi.socketdr.WriterAndReadFile;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *    客户端
 */
public class ClientByJson {
    public static void main(String[] args) {
        try {
//            InetAddress addr=InetAddress.getByName(null);
//            Socket s = new Socket("10.90.86.52",18382);
            Socket s = new Socket("0.0.0.0",8080);
            //构建IO
            InputStream is = s.getInputStream();
            OutputStream os = s.getOutputStream();

            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
            String jsonParams="25409P01_000121";
            //向服务器端发送一条消息
            bw.write(jsonParams+"\n");
            bw.flush();

            //读取服务器返回的消息
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String mess = br.readLine();
            System.out.println("服务器："+mess);
            //截取除报文头以外的部分
            String jsondata = mess.substring(mess.indexOf("["),mess.lastIndexOf("]"));
            System.out.println("json数据："+jsondata);
            //JSON格式转换成json对象,如果是JSON数组用ARRAY解析
            JSONObject object= JSONObject.fromObject(jsondata);
//            JSONArray jsonArray = jsonObject.getJSONArray(mess);

            //获取时间数据
            String time = object.get("time").toString();

            //JSON字符串转Java实体类BesDirectJon
//            BesDirectJon besDirectJon = new BesDirectJon();
//            besDirectJon.setData((List<Data>) object.get("data"));
//            System.out.println("测试JSON类："+besDirectJon.getData());

            //获取data数据转换成JSONArray
            JSONArray jsonarray = object.getJSONArray("data");
            //遍历JSONArray数组
            JSONObject datas = null;
            WriterAndReadFile writerFile = new WriterAndReadFile();
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
            for (int i = 0; i < jsonarray.size(); i++) {
                datas = jsonarray.getJSONObject(i);
                Map<String, String> map = new HashMap<String, String>();
                String ss =datas.getString("code");
                map.put("code",ss );
                //写入本地
                writerFile.writeFile(map,"E:\\Socket测试目录\\out.txt");
                list.add(map);
                System.out.println("单条数据："+map);
            }
//            System.out.println("获取指定时间："+time);
//            System.out.println("获取指定数据："+list);


//            bw.close();
//            br.close();
//            s.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
